package com.mabeijianxi.sample.slice;

import com.mabeijianxi.jianxiexpression.ExpressionShowFragment;
import com.mabeijianxi.sample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.TextField;


public class MainAbilitySlice extends AbilitySlice {

    ExpressionShowFragment expressionShowFragment;
    TextField mText;
    boolean showkeyboard = false;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mText = (TextField) findComponentById(ResourceTable.Id_test_edit);
        expressionShowFragment = (ExpressionShowFragment) findComponentById(ResourceTable.Id_main);

        expressionShowFragment.input(mText);
        mText.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                showkeyboard = true;
            }
        });
        Image image = (Image) findComponentById(ResourceTable.Id_keyboard_switch);
        image.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (showkeyboard) {
                    mText.clearFocus();
                    showkeyboard = false;
                } else {
                    mText.requestFocus();
                    mText.simulateClick();
                    showkeyboard = true;
                }
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    //clearFocus等同于隐藏软键盘
    public static void clearFocus(Component component){
        Component focusedComponent = findFocus(component, Component.FOCUS_NEXT);//尝试向后找焦点控件
        if (focusedComponent != null) {
            focusedComponent.clearFocus();
            return;
        }

        focusedComponent = findFocus(component, Component.FOCUS_PREVIOUS);//尝试向前找焦点控件
        if (focusedComponent != null) {
            focusedComponent.clearFocus();
        }
    }

    //找焦点控件
    public static Component findFocus(Component component, int direction) {
        if (component.hasFocus()) {
            return component;
        }
        Component focusableComponent = component;
        int i = 99;
        while (i-- > 0) {
            focusableComponent = focusableComponent.findNextFocusableComponent(direction);
            if (focusableComponent != null) {
                if (focusableComponent.hasFocus()) {
                    return focusableComponent;
                }
            } else {
                break;
            }
        }
        return null;
    }
}

